package com.woniu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
public class CheckCode {
    //验证码输入
    private static final long serialVersionUID = 1L;
    private Random random=new Random();
    @RequestMapping("checkcode")
    public void getcheckcode(HttpSession httpSession, HttpServletResponse httpServletResponse) throws IOException {
        BufferedImage image =new BufferedImage(120,35,BufferedImage.TYPE_INT_BGR);
        Graphics graphics=image.getGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, 120, 35);
        for(int i=0;i<10;i++) {
            graphics.setColor(getRandomColor());
            int x1=random.nextInt(120);
            int x2=random.nextInt(120);
            int y1=random.nextInt(35);
            int y2=random.nextInt(35);
            graphics.drawLine(x1, y1, x2, y2);
        }
        char[] arrays= {'A','B','C','D','E','F','G','H','J','K','M','N',
                'P','Q','R','S','T','U','V','W','X','Y','Z','2','3',
                '4','5','6','7','8','9'};
        StringBuilder builder =new StringBuilder();
        for(int i=0;i<4;i++) {
            builder.append(arrays[random.nextInt(arrays.length)]);
        }
        httpSession.setAttribute("checkCode", builder.toString());


        graphics.setFont(new Font("黑体", Font.BOLD, 30));
        for(int i=0;i<builder.toString().length();i++) {
            graphics.setColor(getRandomColor());
            char item=builder.toString().charAt(i);
            graphics.drawString(item+"", 5+(i*25), 30);
        }
        ImageIO.write(image, "png", httpServletResponse.getOutputStream());

    }
    private Color getRandomColor() {
        int r=random.nextInt(256);
        int g=random.nextInt(256);
        int b=random.nextInt(256);
        return new Color(r,g,b);
    }
    @RequestMapping("getcheckcode")
    @ResponseBody
    public String getcheckcode(HttpSession httpSession){

        return (String) httpSession.getAttribute("checkCode");
    }
}
